package org.example.test;

import java.util.Random;

public class CaptchaGenerator {

    // 生成随机验证码的方法
    public static String generateCaptcha(int length) {
        StringBuilder captcha = new StringBuilder(length);
        Random random = new Random();

        // 添加数字
        for (int i = 0; i < length / 2; i++) {
            captcha.append(random.nextInt(10));
        }

        // 添加字母（大小写）
        for (int i = 0; i < length - length / 2; i++) {
            int index = random.nextInt(26);
            char randomChar = (char) ('a' + index);
            // 50% 的概率将字母转换为大写
            if (random.nextBoolean()) {
                captcha.append(Character.toUpperCase(randomChar));
            } else {
                captcha.append(randomChar);
            }
        }

        // 混淆验证码，随机打乱顺序
        for (int i = 0; i < captcha.length(); i++) {
            int randomIndex = random.nextInt(captcha.length());
            char temp = captcha.charAt(i);
            captcha.setCharAt(i, captcha.charAt(randomIndex));
            captcha.setCharAt(randomIndex, temp);
        }

        return captcha.toString();
    }

    // 验证验证码的方法
    public static boolean verifyCaptcha(String userInput, String correctCaptcha) {
        return userInput.equalsIgnoreCase(correctCaptcha);
    }

    public static void main(String[] args) {
        // 生成一个6位的验证码
        String captcha = generateCaptcha(6);
        System.out.println("Generated Captcha: " + captcha);

        // 模拟用户输入
        String userInput = "yourInputHere"; // 这里应该是用户从某个界面输入的验证码

        // 验证用户输入的验证码是否正确
        boolean isCorrect = verifyCaptcha(userInput, captcha);
        System.out.println("Captcha is correct: " + isCorrect);
    }
}